#!/bin/bash

# Minecraft面板Linux自动部署脚本
# 作者: Minecraft面板开发团队
# 版本: 1.0.0

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本必须以root权限运行"
        exit 1
    fi
}

# 检查操作系统
check_os() {
    if [[ ! -f /etc/os-release ]]; then
        log_error "无法检测操作系统版本"
        exit 1
    fi
    
    source /etc/os-release
    OS=$ID
    OS_VERSION=$VERSION_ID
    
    log_info "检测到操作系统: $OS $OS_VERSION"
    
    if [[ "$OS" != "ubuntu" && "$OS" != "debian" && "$OS" != "centos" && "$OS" != "rocky" && "$OS" != "almalinux" ]]; then
        log_warning "此脚本主要针对Ubuntu/Debian/CentOS系统，其他系统可能需要手动调整"
    fi
}

# 更新系统
update_system() {
    log_info "更新系统包..."
    
    if [[ "$OS" == "ubuntu" || "$OS" == "debian" ]]; then
        apt-get update
        apt-get upgrade -y
    elif [[ "$OS" == "centos" || "$OS" == "rocky" || "$OS" == "almalinux" ]]; then
        yum update -y
    fi
    
    log_success "系统更新完成"
}

# 安装基础依赖
install_dependencies() {
    log_info "安装基础依赖包..."
    
    if [[ "$OS" == "ubuntu" || "$OS" == "debian" ]]; then
        apt-get install -y \
            curl \
            wget \
            git \
            unzip \
            sudo \
            nginx \
            sqlite3 \
            ufw \
            fail2ban \
            logrotate \
            cron
    elif [[ "$OS" == "centos" || "$OS" == "rocky" || "$OS" == "almalinux" ]]; then
        yum install -y \
            curl \
            wget \
            git \
            unzip \
            sudo \
            nginx \
            sqlite \
            epel-release \
            fail2ban \
            logrotate \
            cronie
    fi
    
    log_success "基础依赖安装完成"
}

# 安装Node.js
install_nodejs() {
    log_info "安装Node.js..."
    
    # 使用国内镜像安装Node.js
    curl -fsSL https://npmmirror.com/mirrors/node/v18.18.0/node-v18.18.0-linux-x64.tar.xz | tar -xJ -C /usr/local
    
    # 创建软链接
    ln -sf /usr/local/node-v18.18.0-linux-x64/bin/node /usr/bin/node
    ln -sf /usr/local/node-v18.18.0-linux-x64/bin/npm /usr/bin/npm
    
    # 设置npm国内镜像
    npm config set registry https://registry.npmmirror.com
    
    # 验证安装
    NODE_VERSION=$(node --version)
    NPM_VERSION=$(npm --version)
    
    log_success "Node.js安装完成: $NODE_VERSION"
    log_success "npm安装完成: $NPM_VERSION"
}

# 安装Docker
install_docker() {
    log_info "安装Docker..."
    
    # 卸载旧版本Docker
    if command -v docker &> /dev/null; then
        log_warning "检测到已安装Docker，正在卸载..."
        apt-get remove -y docker docker-engine docker.io containerd runc || true
        yum remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine || true
    fi
    
    # 安装Docker（使用国内镜像）
    curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
    
    # 配置Docker国内镜像
    mkdir -p /etc/docker
    cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": [
    "https://registry.docker-cn.com",
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  }
}
EOF
    
    # 启动Docker服务
    systemctl enable docker
    systemctl start docker
    
    # 验证安装
    DOCKER_VERSION=$(docker --version)
    log_success "Docker安装完成: $DOCKER_VERSION"
}

# 创建Minecraft面板用户
create_panel_user() {
    log_info "创建Minecraft面板用户..."
    
    # 创建用户
    useradd -r -s /bin/false -d /opt/minecraft-panel minecraft-panel
    
    # 创建必要的目录
    mkdir -p /opt/minecraft-panel
    mkdir -p /opt/minecraft-servers
    mkdir -p /var/log/minecraft-panel
    mkdir -p /etc/minecraft-panel
    
    # 设置权限
    chown -R minecraft-panel:minecraft-panel /opt/minecraft-panel
    chown -R minecraft-panel:minecraft-panel /opt/minecraft-servers
    chown -R minecraft-panel:minecraft-panel /var/log/minecraft-panel
    chmod 755 /opt/minecraft-panel
    chmod 755 /opt/minecraft-servers
    
    log_success "用户和目录创建完成"
}

# 下载并安装Minecraft面板
install_panel() {
    log_info "下载并安装Minecraft面板..."
    
    cd /opt/minecraft-panel
    
    # 下载面板代码（这里假设代码已经在当前目录，实际使用时需要从Git仓库下载）
    # git clone https://github.com/your-repo/minecraft-panel.git .
    
    # 复制当前代码到安装目录
    cp -r /home/admin/workspace/minecraft-panel/* ./
    
    # 安装依赖
    sudo -u minecraft-panel npm install --production
    
    # 创建环境配置文件
    cp .env.example .env
    
    # 生成随机密钥
    SESSION_SECRET=$(openssl rand -hex 32)
    sed -i "s/your-secret-key-here-change-this-in-production/$SESSION_SECRET/g" .env
    
    # 设置权限
    chown -R minecraft-panel:minecraft-panel /opt/minecraft-panel
    chmod +x /opt/minecraft-panel/app.js
    
    log_success "Minecraft面板安装完成"
}

# 配置Nginx
configure_nginx() {
    log_info "配置Nginx..."
    
    cat > /etc/nginx/sites-available/minecraft-panel << EOF
server {
    listen 80;
    server_name _;
    
    client_max_body_size 100M;
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
    }
    
    location /socket.io/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }
}
EOF
    
    # 启用站点
    ln -sf /etc/nginx/sites-available/minecraft-panel /etc/nginx/sites-enabled/
    rm -f /etc/nginx/sites-enabled/default
    
    # 测试Nginx配置
    nginx -t
    
    # 重启Nginx
    systemctl enable nginx
    systemctl restart nginx
    
    log_success "Nginx配置完成"
}

# 创建systemd服务
create_systemd_service() {
    log_info "创建systemd服务..."
    
    cat > /etc/systemd/system/minecraft-panel.service << EOF
[Unit]
Description=Minecraft Panel
After=network.target docker.service

[Service]
Type=simple
User=minecraft-panel
WorkingDirectory=/opt/minecraft-panel
ExecStart=/usr/bin/node app.js
Restart=always
RestartSec=10
Environment=NODE_ENV=production
Environment=PORT=3000

# 安全设置
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/minecraft-panel
ReadWritePaths=/opt/minecraft-servers
ReadWritePaths=/var/log/minecraft-panel

[Install]
WantedBy=multi-user.target
EOF
    
    # 重新加载systemd
    systemctl daemon-reload
    
    # 启用服务
    systemctl enable minecraft-panel
    
    log_success "systemd服务创建完成"
}

# 配置防火墙
configure_firewall() {
    log_info "配置防火墙..."
    
    if command -v ufw &> /dev/null; then
        # Ubuntu/Debian UFW
        ufw --force enable
        ufw allow 22/tcp
        ufw allow 80/tcp
        ufw allow 443/tcp
        log_success "UFW防火墙配置完成"
    elif command -v firewall-cmd &> /dev/null; then
        # CentOS/RHEL FirewallD
        systemctl enable firewalld
        systemctl start firewalld
        firewall-cmd --permanent --add-service=ssh
        firewall-cmd --permanent --add-service=http
        firewall-cmd --permanent --add-service=https
        firewall-cmd --reload
        log_success "FirewallD防火墙配置完成"
    else
        log_warning "未检测到防火墙工具，请手动配置防火墙"
    fi
}

# 配置SSL证书（Let's Encrypt）
configure_ssl() {
    log_info "配置SSL证书..."
    
    # 安装Certbot
    if [[ "$OS" == "ubuntu" || "$OS" == "debian" ]]; then
        apt-get install -y certbot python3-certbot-nginx
    elif [[ "$OS" == "centos" || "$OS" == "rocky" || "$OS" == "almalinux" ]]; then
        yum install -y certbot python3-certbot-nginx
    fi
    
    log_info "SSL证书配置工具已安装，请手动运行以下命令获取证书："
    log_info "certbot --nginx -d your-domain.com"
    log_info "将 your-domain.com 替换为您的域名"
}

# 配置日志轮转
configure_logrotate() {
    log_info "配置日志轮转..."
    
    cat > /etc/logrotate.d/minecraft-panel << EOF
/var/log/minecraft-panel/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 minecraft-panel minecraft-panel
    postrotate
        systemctl reload minecraft-panel
    endscript
}
EOF
    
    log_success "日志轮转配置完成"
}

# 配置自动备份
configure_backup() {
    log_info "配置自动备份..."
    
    cat > /etc/cron.daily/minecraft-panel-backup << EOF
#!/bin/bash
# Minecraft面板自动备份脚本

BACKUP_DIR="/opt/minecraft-panel/backups"
DATE=\$(date +%Y%m%d_%H%M%S)
mkdir -p \$BACKUP_DIR

# 备份数据库
cp /opt/minecraft-panel/database.sqlite \$BACKUP_DIR/database_\$DATE.sqlite

# 备份配置文件
tar -czf \$BACKUP_DIR/config_\$DATE.tar.gz -C /opt/minecraft-panel .env

# 清理30天前的备份
find \$BACKUP_DIR -name "*.sqlite" -mtime +30 -delete
find \$BACKUP_DIR -name "*.tar.gz" -mtime +30 -delete

echo "备份完成: \$DATE"
EOF
    
    chmod +x /etc/cron.daily/minecraft-panel-backup
    
    log_success "自动备份配置完成"
}

# 显示安装结果
show_installation_result() {
    log_success "Minecraft面板安装完成！"
    echo
    echo "=========================================="
    echo "  Minecraft面板安装信息"
    echo "=========================================="
    echo "面板访问地址: http://$(curl -s ifconfig.me)"
    echo "面板安装目录: /opt/minecraft-panel"
    echo "服务器数据目录: /opt/minecraft-servers"
    echo "日志目录: /var/log/minecraft-panel"
    echo
    echo "首次使用请访问: http://$(curl -s ifconfig.me)/init"
    echo "完成初始化设置后即可使用面板"
    echo
    echo "常用命令:"
    echo "  启动面板: systemctl start minecraft-panel"
    echo "  停止面板: systemctl stop minecraft-panel"
    echo "  重启面板: systemctl restart minecraft-panel"
    echo "  查看状态: systemctl status minecraft-panel"
    echo "  查看日志: journalctl -u minecraft-panel -f"
    echo
    echo "=========================================="
}

# 主函数
main() {
    echo "=========================================="
    echo "  Minecraft面板Linux自动部署脚本"
    echo "=========================================="
    echo
    
    # 检查系统环境
    check_root
    check_os
    
    # 安装基础组件
    update_system
    install_dependencies
    install_nodejs
    install_docker
    
    # 配置用户和目录
    create_panel_user
    
    # 安装面板
    install_panel
    
    # 配置服务
    configure_nginx
    create_systemd_service
    configure_firewall
    configure_logrotate
    configure_backup
    
    # 启动服务
    systemctl start minecraft-panel
    
    # 显示安装结果
    show_installation_result
    
    log_success "所有安装步骤完成！"
}

# 运行主函数
main "$@"